import React, { ReactElement, useMemo, useContext, useEffect } from 'react';
import { BackHandler, Image, Text, View } from 'react-native';

import Button from '../../../../components/Button';
import NavBar from '../../../../components/NavBar';
import Notch, { NotchType } from '../../../../components/Notch';
import { openMicrophoneWhite } from '../../../../constant/resource';
import { secondToMinute } from '../../../../util/transformDate';
import { handleBackButton, setRecording, startRecord } from '../../actions';
import { Store } from '../../reducer';
import Recording from '../Recording';
import Ripple from '../Ripple';
import styles from './style';

export default (): ReactElement => {
  const { state } = useContext(Store);
  const { showRecord, recording, recordDuration } = state;

  useEffect((): (() => void) => {
    if (!showRecord) return (): void => {};
    BackHandler.addEventListener('hardwareBackPress', handleBackButton);
    return (): void => {
      BackHandler.removeEventListener('hardwareBackPress', handleBackButton);
    };
  }, [showRecord]);

  return useMemo((): ReactElement => {
    if (!showRecord) return <View />;
    return (
      <Notch style={styles.container} type={NotchType.Top}>
        <NavBar title="语音回答" backAction={handleBackButton} />
        <View style={styles.content}>
          <Ripple recording={recording} />
          <Text
            style={[styles.volumeNumber, recording ? {} : styles.notRecord]}
          >
            {secondToMinute(Math.round(recordDuration))}
          </Text>
          {recording ? (
            <Recording />
          ) : (
            <View style={styles.startContent}>
              <Button
                style={styles.notRecordContent}
                onPress={(): void => {
                  startRecord();
                  setRecording(true);
                }}
              >
                <Image
                  source={openMicrophoneWhite}
                  style={styles.microphone}
                  resizeMode="contain"
                />
              </Button>
            </View>
          )}
          {!recording && (
            <Text style={styles.desc}>点击按钮，录制你的回答</Text>
          )}
        </View>
      </Notch>
    );
  }, [recordDuration, recording, showRecord]);
};
